<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene" />
    <el-card style="margin: 10px 0px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="categortStore.categoryInfo.categoryId3 ? false : true"
          @click="addAttr"
        >
          添加属性
        </el-button>
        <el-table border style="margin: 10px 0px" :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="150"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="scope">
              <el-tag
                v-for="item in scope.row.attrValueList"
                :key="item.id"
                style="margin: 5px"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <!-- 修改已有属性按钮 -->
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="updaAttr(scope.row)"
              ></el-button>
              <!-- 气泡弹窗 -->
              <el-popconfirm
                :title="`你确定要删除${scope.row.id}?`"
                @confirm="deleteAttr(scope.row.id)"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 展示添加属性与修改数据的结构 -->
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性的名称"
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="Plus"
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button>取消</el-button>
        <el-table
          border
          style="margin: 10px 0px"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            width="80"
            align="center"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                placeholder="请您输入属性值名称"
                v-model="row.valueName"
                v-if="row.flag"
                @blur="toLook(row, $index)"
                :ref="(vc: any) => (inputArr[$index] = vc)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="属性操作">
            <template #="{ row, index }">
              <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="attrParams.attrValueList.splice(index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >
          保存
        </el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import useCategoryStore from '@/store/modules/category'
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqRemoveAttr,
} from '@/services/product/attr'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import type {
  AttrResponseData,
  Attr,
  AttrValue,
} from '@/services/product/attr/type'
import { ElMessage } from 'element-plus'

let categortStore = useCategoryStore()

let inputArr = ref<any>([])

// 展示添加与修改属性
let scene = ref<number>(0)

// 收集新增属性的数据
let attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
})

// 监听三级分类ID的变化，有ID就请求数据
watch(
  () => categortStore.categoryInfo.categoryId3,
  () => {
    // 清空上一次查询的
    attrArr.value = []
    // 保证三级分类有id再发送请求
    if (!categortStore.categoryInfo.categoryId3) return
    // 获取分类的id
    getAtrr()
  },
)

let attrArr = ref<Attr[]>([])
// 获取已有的属性值和属性方法
const getAtrr = async () => {
  const { categoryId1, categoryId2, categoryId3 } = categortStore.categoryInfo
  const res: AttrResponseData = await reqAttr(
    categoryId1,
    categoryId2,
    categoryId3,
  )
  if (res.code == 200) {
    attrArr.value = res.data
  }
}

// 点击添加按钮切换
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: categortStore.categoryInfo.categoryId3,
    categoryLevel: 3,
  })
  scene.value = 1
}

// 修改已有属性
const updaAttr = (row: Attr) => {
  scene.value = 1
  // 将已有的属性赋值给attrParams
  // es6语法，进行对象合并，把row给attrParams
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

// 取消按钮事件
const cancel = () => {
  scene.value = 0
}
// 添加属性值按钮
const addAttrValue = () => {
  // 点击添加属性值按钮，就添加一个属性对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, //编辑或查看模式的切换
  })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
// 添加属性保存按钮
const save = async () => {
  const res: any = await reqAddOrUpdateAttr(attrParams)
  if (res.code == 200) {
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
      // 再次获取已有的属性值
    })
    getAtrr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
// 属性值名称失去焦点触发
const toLook = (row: AttrValue, $index: number) => {
  // 非法情况1 名称为空
  if (row.valueName.trim() == '') {
    // 删除属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  // 非法情况2 重复属性名称
  let repeat = attrParams.attrValueList.find((item) => {
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    // 将重复的属性值去掉
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  row.flag = false
}

// 点击属性名字，变为编辑模式
const toEdit = (row: AttrValue, $index: string) => {
  row.flag = true
  // 监听更新后的dom
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

// 删除某一个已有的属性方法
const deleteAttr = async (attrId: number) => {
  const res = await reqRemoveAttr(attrId)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    // 获取一次已有的属性与属性值
    getAtrr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

// 路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  // 重置仓库的数据
  categortStore.$reset()
})
</script>

<style lang="scss" scoped></style>
